package com.zzyl.intercept;

import cn.hutool.core.map.MapUtil;
import com.github.pagehelper.Constant;
import com.zzyl.constant.Constants;
import com.zzyl.constant.SecurityConstant;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class UserInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是handler,Controller中的方法就是handler
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        // 获取token
        String token = request.getHeader(SecurityConstant.USER_TOKEN);
        if(ObjectUtil.isEmpty(token)){
            throw new BaseException("小程序","401",null,"小程序token失效，请重新登录！");
        }

        //解析token
        Map<String,Object> claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        if(ObjectUtil.isEmpty(token)){
            throw new BaseException("小程序","401",null,"小程序token失效，请重新登录！");
        }

        //获取数据
//        Long userId = (Long) claims.get(Constants.JWT_USERID);  //强转
        //用hutool工具转
        Long userId = MapUtil.get(claims, Constants.JWT_USERID, Long.class);
        if(ObjectUtil.isEmpty(token)){
            throw new BaseException("小程序","401",null,"小程序token失效，请重新登录！");
        }

        //存储到threadlocal中
        UserThreadLocal.set(userId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
